/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        return inorderSuccessor(root, p.val, null);
    }
    public TreeNode inorderSuccessor(TreeNode root, int val, TreeNode ans) {
        if (root == null) {
            return ans;
        }
        if (val > root.val) {
            return inorderSuccessor(root.right, val, ans);
        } else if (val < root.val) {
            if (ans == null || ans.val > root.val) {
                ans = root;
            }
            return inorderSuccessor(root.left, val, ans);
        } else {
            if (root.right != null) {
                ans = root.right;
                if (root.right.left != null) {
                    ans = root.right.left;
                    while (ans.left != null) {
                        ans = ans.left;
                    }
                }
            }
            return ans;
        }
    }
}
